from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QHBoxLayout
from PyQt5.QtCore import Qt, QTimer
from models.entities import Battle
from typing import List


class BattlesView(QWidget):
    def __init__(self, battles: List[Battle]):
        super().__init__()
        self._battles = battles
        self._current = 0
        self._timer = QTimer(self)
        self._timer.setInterval(33)  # ~30 fps
        self._timer.timeout.connect(self._tick)

        layout = QVBoxLayout(self)
        self.title = QLabel("重大战役")
        self.title.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.title)

        self.content = QLabel("选择一场战役进行回放")
        self.content.setWordWrap(True)
        layout.addWidget(self.content, 1)

        controls = QHBoxLayout()
        self.btn_prev = QPushButton("上一场")
        self.btn_next = QPushButton("下一场")
        self.btn_play = QPushButton("开始回放")
        self.btn_prev.clicked.connect(self.prev)
        self.btn_next.clicked.connect(self.next)
        self.btn_play.clicked.connect(self.play)
        for b in [self.btn_prev, self.btn_next, self.btn_play]:
            controls.addWidget(b)
        layout.addLayout(controls)

        self._phase = 0

    def set_data(self, battles: List[Battle]):
        self._battles = battles

    def prev(self):
        if not self._battles:
            return
        self._current = (self._current - 1) % len(self._battles)
        self._update_label()

    def next(self):
        if not self._battles:
            return
        self._current = (self._current + 1) % len(self._battles)
        self._update_label()

    def play(self):
        if not self._battles:
            return
        self._phase = 0
        self._timer.start()

    def _tick(self):
        # Simple text-based animation phase update
        self._phase += 1
        if self._phase > 120:  # ~4 seconds
            self._timer.stop()
        self._update_label()

    def _update_label(self):
        if not self._battles:
            self.content.setText("暂无战役数据")
            return
        b = self._battles[self._current]
        dots = '.' * ((self._phase // 10) % 4)
        self.content.setText(f"{b.name}（{b.year or ''}）\n{b.summary}\n回放中{dots}")

